package com.tcppag.linebased;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;

import java.util.Random;

/**
 * @author 罗俊华
 * @date 2021/8/27 - 9:20 上午
 */
public class LineClient {

    static Random random = new Random();

    public static void main(String[] args) {


        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup(1))
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {

                        ch.pipeline().addLast(new LoggingHandler())
                                .addLast(new StringEncoder());

                    }
                }).connect("localhost", 9909);

        channelFuture.addListener((ChannelFuture future) -> {

            Channel channel = future.channel();

            for (int i = 0; i < 10; i++) {
                channel.write(getRandomStrLine(20));
            }

            channel.flush();


        });

    }


    /**
     * 获取一行随机字符串，这行字符串以换行符(\n )结尾
     *
     * @return
     */
    public static String getRandomStrLine(int maxLength) {

        int length = Math.max(1,random.nextInt(maxLength )) ;

        StringBuilder builder = new StringBuilder(length);
        char c = (char) random.nextInt(127);
        for (int i = 0; i < length - 1; i++) {
            builder.append(c);
        }

        builder.append("\n");

        return builder.toString();
    }


}
